package cup.common.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @author : ruoyu
 * @date : 2022/7/26
 */
public class GeneratorMapByList {

	public static <K, T> Map<K, T> generator(Supplier<List<T>> supplier, String key,Class<K> kClass) {
		Map<K, T> result = new HashMap<>();
		List<T> ts = supplier.get();
		String methodStr = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
		if (!CollectionUtils.isEmpty(ts)) {
			T t1 = ts.get(0);
			if(!(t1 instanceof Map)){
				Field field = ReflectUtil.getField(t1.getClass(), key);
				if (null == field) {
					throw new IllegalArgumentException("无效的参数[" + key + "]");
				}
				Method method = ReflectUtil.getMethod(t1.getClass(), methodStr);
				if (null == method) {
					throw new NullPointerException("未查询到方法:[" + methodStr + "]");
				}
				for (T t : ts) {
					K dataK = ReflectUtil.invoke(t, methodStr);
					result.put(dataK,t);
				}
			}else{
				for (T t : ts) {
					Map map= (Map) t;
					K k = MapUtil.get(map, key, kClass);
					result.put(k,t);
				}
			}
		}
		return result;
	}
}
